package crons

import (
	"context"
	"devops-super/internal/dao"
	"devops-super/internal/model/do"
	"devops-super/internal/model/entity"
	"devops-super/utility/util/dbUtil"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
)

func (s *sCron) DoSummaryDatabaseSize(ctx context.Context) (err error) {
	cols := dao.AppDistributeTables.Columns()
	pageSize := 2000
	page := 1
	for {
		pageOffset := (page - 1) * pageSize
		var rows []*entity.AppDistributeTables
		err = dao.AppDistributeTables.Ctx(ctx).WhereNot(cols.SummaryStatus, 1).Offset(pageOffset).Limit(pageSize).Scan(&rows)
		if err != nil {
			return
		}
		for _, row := range rows {
			dbConnGroup := row.ServerKey
			table := row.Table
			count, err := g.DB(dbConnGroup).Model(table).Count()
			if err != nil {
				continue
			}
			size, err := dbUtil.GetThisTableUsedSize(ctx, dbConnGroup, table)
			if err != nil {
				continue
			}
			status := 0
			if row.TimeEnd < uint64(gtime.Now().Unix()-3600) { //如果结束时间比当前时间少，并且给1小时的缓冲，说明不会再有入库了
				status = 1
			}
			_, err = dao.AppDistributeTables.Ctx(ctx).WherePri(row.Id).Update(do.AppDistributeTables{
				UpdatedAt:     gtime.Now(),
				TotalAmount:   count,
				TotalSize:     size,
				SummaryStatus: status,
			})
			if err != nil {
				return err
			}
		}
		if len(rows) < pageSize {
			break
		}
		page++
	}
	return
}
